<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="btn-add">
        <el-button
        icon="el-icon-circle-plus-outline"
        type="button"
        class="el-button el-button--primary"
        @click="addInOrOut"
        >
            新增</el-button
        >
    </div>

    <!-- 新增数据弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="showAdd"
      @close="showAdd = false"
      width="65%"
    >
        <el-form :model="createForm" :inline="true" ref="createForm" :rules="addRules">
            <el-form-item label="产品品号" prop="produceNo" >
                <el-select
                  clearable
                  v-model="createForm.produceNo" 
                  placeholder="请选择产品品号" 
                  @change="produceNoChange"
                  style="width: 150px;margin-right:15px;">
                      <el-option
                      :value="item"
                      :label="item" v-for="(item,index) in produceNoList" 
                      :key="index"/>
                </el-select>
            </el-form-item>
            <el-form-item label="品名" prop="produceName" >
                <el-input v-model="createForm.produceName" autosize disabled/>
            </el-form-item>
            <el-form-item label="规格" prop="specification" >
                <el-input v-model="createForm.specification" autosize disabled style="width: 120px;"/>
            </el-form-item>
            <el-form-item label="工艺顺序" prop="processOrder" >
                <el-select
                  clearable
                  v-model="createForm.processOrder"
                  @change="processOrderChange"
                  @focus="processFocus"
                  placeholder="请选择工艺顺序"
                  style="width: 150px;">
                      <el-option
                      :label="item.facilityProcess + '—' + item.produceName" v-for="(item,index) in processingList"
                      :value="index"
                      :key="index"/>
                </el-select>
            </el-form-item>
            <el-form-item label="拧紧顺序" prop="processingSequence" >
                <el-input v-model="createForm.processingSequence" autosize style="width: 120px"/>
            </el-form-item>
            <el-form-item label="螺钉规格" prop="specs" >
                <el-select
                  clearable
                  v-model="createForm.specs"
                  @focus="boltFocus"
                  @change="boltchange"
                  placeholder="请选择螺钉规格"
                  style="width: 150px;margin-right:15px;">
                      <el-option
                      :label="item.facilityBarcodeChineseName" v-for="(item,index) in boltList"
                      :value="index"
                      :key="index"/>
                </el-select>
            </el-form-item>
            <el-form-item label="螺钉数量" prop="qty" >
                <el-input v-model="createForm.qty" autosize style="width: 120px"/>
            </el-form-item>
            <el-form-item label="最小角度" prop="minAngle" >
                <el-input v-model="createForm.minAngle" autosize style="width: 120px"/>
            </el-form-item>
            <el-form-item label="最大角度" prop="maxAngle" >
                <el-input v-model="createForm.maxAngle" autosize style="width: 120px"/>
            </el-form-item>
            <el-form-item label="最小扭矩" prop="minTorque" >
                <el-input v-model="createForm.minTorque" autosize style="width: 120px"/>
            </el-form-item>
            <el-form-item label="旋入扭矩" prop="spinTorque" >
                <el-input v-model="createForm.spinTorque" autosize style="width: 120px"/>
            </el-form-item>
            <el-form-item label="目标扭矩" prop="targetTorque" >
                <el-input v-model="createForm.targetTorque" autosize style="width: 120px"/>
            </el-form-item>
            <el-form-item label="最大扭矩" prop="maxTorque" >
                <el-input v-model="createForm.maxTorque" autosize style="width: 120px"/>
            </el-form-item>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
            >确 定</el-button
            >
        </div>
    </el-dialog>


    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->
        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.produceNo) }"
            v-model="param.produceNo"
            placeholder="产品品号"
        ></el-input>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>

    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="加工顺序"  prop="processingSequence" align="center"/>
      <el-table-column label="产品品号"  prop="produceNo" align="center"/>
      <el-table-column label="品名"  prop="produceName" align="center"/>
      <el-table-column label="规格"  prop="specification" align="center"/>
      <el-table-column label="工序顺序"  prop="processOrder" align="center"/>
      <el-table-column label="螺钉规格"  prop="specs" align="center"/>
      <el-table-column label="螺钉数量"  prop="qty" align="center"/>
      <el-table-column label="最小角度"  prop="minAngle" align="center"/>
      <el-table-column label="最大角度"  prop="maxAngle" align="center"/>
      <el-table-column label="旋入扭矩"  prop="spinTorque" align="center"/>
      <el-table-column label="目标扭矩"  prop="targetTorque" align="center"/>
      <el-table-column label="最小扭矩"  prop="minTorque" align="center"/>
      <el-table-column label="最大扭矩"  prop="maxTorque" align="center"/>
      <el-table-column label="维护人"  prop="createBy" align="center"/>
      <el-table-column label="修改时间"  prop="updateTime" align="center"/>
      <!-- <el-table-column label="修改原因"  prop="" align="center"/>
      <el-table-column label="是否有效"  prop="" align="center"/> -->
      <el-table-column label="操作" fixed="right" align="center" width="130">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
                </div>
            </template>
      </el-table-column>
    </el-table>

    <!-- 修改数据弹窗 -->
    <el-dialog
      title="修改工序信息"
      :visible.sync="showupd"
      @close="showupd = false"
      width="35%"
    >
        <el-form :inline="true" :model="updForm" ref="updForm" :rules="addRules">
            <el-form-item label="条码" prop="code" >
                <el-input v-model="updForm.code" type="textarea" autosize  style="width: 150px"/>
            </el-form-item>
            <el-form-item label="点检内容" prop="content" >
                <el-input v-model="updForm.content" type="textarea" autosize style="width: 300px"/>
            </el-form-item>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showupd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="updprocess('updForm')"
            >修改</el-button
            >
        </div>
    </el-dialog>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <!-- <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button> -->

  </div>
</template>

<script>
import { screwTighteningList,screwTighteningAdd,screwTighteningEdit,configurationUpd,configurationDel,screwTightening,getMaterialBom,listByType } from "@/api/processRoute"
export default {
    name: 'productMaintenance',
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                produceNo: ''                
            },
            total: 0,                                      //数据的总数
            tableInfo: [],
            tableMX:[],
            showMX: false,
            loadingList: false,
            loading: false,
            centerList: [],                         //工作中心列表
            createForm: {},
            updForm: {},
            props: { multiple: true },
            // 表单校验
            addRules: {
                produceNo: [
                    { required: true, message: "产品品号不能为空!", trigger: "change" },
                ],
                produceName: [
                    { required: true, message: "品名不能为空!", trigger: "change" },
                ],
                specification: [
                    { required: true, message: "规格不能为空!", trigger: "change" },
                ],
                processOrder: [
                    { required: true, message: "工艺顺序不能为空!", trigger: "change" },
                ],
                processingSequence: [
                    { required: true, message: "拧紧顺序不能为空!", trigger: "change" },
                ],
                specs: [
                    { required: true, message: "螺钉规格不能为空!", trigger: "change" },
                ],
                qty: [
                    { required: true, message: "螺钉数量不能为空!", trigger: "change" },
                ],
                minTorque: [
                    { required: true, message: "最小扭矩不能为空!", trigger: "change" },
                ],
                maxTorque: [
                    { required: true, message: "最大扭矩不能为空!", trigger: "change" },
                ],
                spinTorque: [
                    { required: true, message: "旋入扭矩不能为空!", trigger: "change" },
                ],
                targetTorque: [
                    { required: true, message: "目标扭矩不能为空!", trigger: "change" },
                ],
                minAngle: [
                    { required: true, message: "最小角度不能为空!", trigger: "change" },
                ],
                maxAngle: [
                    { required: true, message: "最大角度不能为空!", trigger: "change" },
                ],
            },
            selectedItem: null,
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
            barcodeType1List: [],
            accessTypeList: ['出库','入库'],
            barcodeType3List: [],
            produceNoList: [],
            produceNoObj: {},
            processingList: [],
            boltList: [],
            title:''
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.param)
            let data = await screwTighteningList(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.total = data.data.count
            this.tableInfo = data.data
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            processingSequence: '加工顺序',
            produceNo: '产品品号',
            produceName: '品名',
            specification: '规格',
            processOrder: '工序顺序',
            specs: '螺钉规格',
            qty: '螺钉数量',
            minAngle: '最小角度',
            maxAngle: '最大角度',
            spinTorque: '旋入扭矩',
            targetTorque: '目标扭矩',
            minTorque: '最小扭矩',
            maxTorque: '最大扭矩',
            createBy: '维护人',
            updateTime: '修改时间',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delprocess(row,index)
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })
            })
        },
        async delprocess(row,index){
          let res = await configurationDel({id: row.id})
          if(res.code == '500') return
          if(res.code != '1') return this.$message.error(res.msg)
          this.tableInfo.splice(index,1)
          this.$message.success(res.msg)
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          if(this.param.produceNo){ query.produceNo = this.param.produceNo}
          let arr = await screwTighteningList(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.length){
            this.loading = false
            this.$message.error('暂无数据')
          }
          const { header, data } = this.transformDat(this.setSort(arr.data))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '产品工序数据维护', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              processingSequence: item.processingSequence,
              produceNo: item.produceNo,
              produceName: item.produceName,
              specification: item.specification,
              processOrder: item.processOrder,
              specs: item.specs,
              qty: item.qty,
              minTorque: item.minTorque,
              maxTorque: item.maxTorque,
              targetTorque: item.targetTorque,
              spinTorque: item.spinTorque,
              minAngle: item.minAngle,
              maxAngle: item.maxAngle,
              createBy: item.createBy,
              updateTime: item.updateTime,
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {
                produceNo:''
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitprocess()
                } else {
                    return false
                }
            })
        },
        async submitprocess(){
            let query = Object.assign({},this.createForm)
            let data
            if(this.title == '新增'){
               data = await screwTighteningAdd(query)
            }else{
               data = await screwTighteningEdit(query)
            }
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.resetForm()
            this.showAdd = false
            this.handleFilter()
        },
        resetForm(){
             this.$refs.createForm.resetFields();
        },
        handleEdit(row){
            this.createForm = Object.assign({},row)
            this.title = '修改'
            this.showAdd = true
        },
        // 提交表单之前先进行验证
        updprocess(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.configurationUpd()
                } else {
                    return false
                }
            })
        },
        async configurationUpd(){
            let query = Object.assign({},this.updForm)
            delete query.createTime
            delete query.updateTime
            const data = await configurationUpd(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.showupd = false
            this.handleFilter()
            this.$message.success(errMsg)
        },
        addInOrOut(){
            this.title = '新增'
            this.showAdd = true
        },
        async produceNoChange(e){
            Object.keys(this.produceNoObj).forEach(key => {
              if(e == key){
                this.processingList = this.produceNoObj[key]
              }
              this.$set(this.createForm,'produceName','')
              this.$set(this.createForm,'specification','')
              this.$set(this.createForm,'processOrder','')
              this.$set(this.createForm,'toolProcessId','')
              console.log('key:', key, 'value:', this.produceNoObj[key]);
            });
        },
        async getProduceNo(){
            const res = await screwTightening({})
            console.log('res',res)
            this.produceNoObj = res.data
            this.produceNoList = Object.keys(res.data);
        },
        processOrderChange(index){
            console.log(this.processingList[index]);
            this.createForm.produceName = this.processingList[index].produceName
            this.createForm.specification = this.processingList[index].facilityBarcodeType3
            this.createForm.processOrder = this.processingList[index].facilityProcess
            this.createForm.toolProcessId = this.processingList[index].id
        },
        // 获取焦点
        async processFocus(){
            if(this.title == '修改'){
                if(!this.createForm.produceNo) return this.$message.warning('请填写品号！')
                const res = await screwTightening({facilityTechnologyNo: this.createForm.produceNo})
                this.processingList = res.data[this.createForm.produceNo]
                console.log('res',this.processingList)
                this.produceNoObj = res.data
            }
        },
        async boltFocus(){
            let query = {
                facilityBarcodeType: '螺钉'
            }
            const res = await listByType(query)
            console.log('res',res);
            this.boltList = res.data
        },
        // 螺钉修改
        boltchange(index){
            console.log(this.boltList[index]);
            this.createForm.specs = this.boltList[index].facilityBarcodeChineseName
            this.createForm.facilityBarcodeName = this.boltList[index].facilityBarcodeName
        }
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
        this.getProduceNo()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>
